package com.shujia.core

import com.shujia.core.Demo07GroupBy.StuGrp
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD

object Demo14Join {
  def main(args: Array[String]): Unit = {
    /**
     * join ：适合两份KV格式的RDD之间进行关联
     */
    val conf: SparkConf = new SparkConf()
    conf.setAppName("Demo14Join")
    conf.setMaster("local")

    val sc: SparkContext = new SparkContext(conf)

    val stuLineRDD: RDD[String] = sc.textFile("spark/data/students.txt")

    // 将每条数据转换成样例类对象
    val stuRDD: RDD[StuGrp] = stuLineRDD.map(line => {
      val splits: Array[String] = line.split(",")
      StuGrp(splits(0), splits(1), splits(2).toInt, splits(3), splits(4))
    })

    // 加载分数的数据 以id作为key，整体作为value
    val scoreLineRDD: RDD[(String, String)] = sc.textFile("spark/data/score.txt").map(line => (line.split(",")(0), line.replace(",", "|")))
    scoreLineRDD.foreach(println)

    // 使用id关联学生、分数数据 [id,name,clazz,subject,score]
    stuRDD
      .map(stu => (stu.id, stu.name + "|" + stu.clazz))
      .join(scoreLineRDD)
      .map(kv=>{
        val id: String = kv._1
        val nameAndClazz: String = kv._2._1
        val scoLine: String = kv._2._2
        val infoSplits: Array[String] = nameAndClazz.split("\\|")
        val scoSplits: Array[String] = scoLine.split("\\|")
        s"$id,${infoSplits(0)},${infoSplits(1)},${scoSplits(1)},${scoSplits(2)}"
      }).foreach(println)

  }

}
